#!/usr/bin/env python
from kubernetes import client
from utils.getClient import getClient

myClient = getClient()

def listAllPod(client:client):
    # Do calls
    apiObj = client.CoreV1Api()
    print("Listing pods with their IPs:")
    ret = apiObj.list_pod_for_all_namespaces(watch=False)
    for i in ret.items:
        print("%s\t%s\t%s" %
            (i.status.pod_ip, i.metadata.namespace, i.metadata.name))

def createNamespace(client:client):
    apiObj = client.CoreV1Api()
    data = {
        "apiVersion": "v1",
        "kind": "Namespace",
        "metadata": {
            "name": "test123"
        }
    }
    ret = apiObj.create_namespace(body=data)
    print (ret)

def create_deployment_object(client:client):
    # Configureate Pod template container
    container = client.V1Container(
        name="nginx",
        image="nginx:latest",
        ports=[client.V1ContainerPort(container_port=80)],
        resources=client.V1ResourceRequirements(
            requests={"cpu": "100m", "memory": "200Mi"},
            limits={"cpu": "500m", "memory": "500Mi"}
        )
    )
    # Create and configurate a spec section
    template = client.V1PodTemplateSpec(
        metadata=client.V1ObjectMeta(labels={"app": "nginx"}),
        spec=client.V1PodSpec(containers=[container]))
    # Create the specification of deployment
    spec = client.V1DeploymentSpec(
        replicas=2,
        template=template,
        selector={'matchLabels': {'app': 'nginx'}})
    # Instantiate the deployment object
    deployment = client.V1Deployment(
        api_version="apps/v1beta1",
        kind="Deployment",
        metadata=client.V1ObjectMeta(name="nginx-deployment"),
        spec=spec)

    return deployment


def createDeployment(client:client):
    # Create deployements
    objApi = client.AppsV1beta1Api()
    ret = objApi.create_namespaced_deployment(
        body=create_deployment_object(client),
        namespace="default")
    print("Deployment created. status='%s'" % str(ret.status))

def createDeploymentWithYml(client:client):
    import yaml
    with open("ymldir/nginxDeploy.yaml") as f:
        conf = yaml.safe_load(f)
        apiObj = client.AppsV1beta1Api()
        resp = apiObj.create_namespaced_deployment(
            body=conf, namespace="default")
        print("Deployment created. status='%s'" % resp.metadata.name)




if __name__ == "__main__":
    createDeploymentWithYml(myClient)
